package com.service.scheduling.utils;

import com.alibaba.fastjson.JSONObject;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Strings;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class EthNodeUtil {


    private Web3j web3jNode = Web3j.build(new HttpService("https://mainnet.infura.io/v3/cee41b881e9b4a369cb3df8efe61fa35"));
    private Web3j web3jRpc = Web3j.build(new HttpService("http://localhost:8545"));


    /**
     * 获取最新的区块高度
     * @return
     */
    public BigInteger getBlockNumber() throws IOException {
        //获取当前块高度
        BigInteger currentBlockNumber = web3jNode.ethBlockNumber().send().getBlockNumber();
//        //运行初始化
//        if (lastBlockNumber == null || currentBlockNumber.subtract(lastBlockNumber).compareTo(BigInteger.valueOf(100)) > 0) {
//            lastBlockNumber = BigInteger.valueOf(currentBlockNumber.longValue());
//            return;
//        }
        return currentBlockNumber;
    }


    public EthBlock getBlockEthBlock(Integer blockNumber) throws IOException {
        DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(blockNumber);
        Request<?, EthBlock> request = web3jNode.ethGetBlockByNumber(defaultBlockParameter, true);
        EthBlock ethBlock = request.send();
        return ethBlock;
    }

    public void scanTrans() {
//        List<EthBlock.TransactionResult> transactions = web3jNode.ethGetBlockByNumber(getBlockNumber()).getResult().getTransactions();
//        for (EthBlock.TransactionResult tx : transactions) {
//            EthBlock.TransactionObject transaction = (EthBlock.TransactionObject) tx.get();
//            if (transaction.getValue().compareTo(BigInteger.ZERO) > 0) {
//                if (Strings.isEmpty(transaction.getTo())) {
//                    log.info("转入地址为空跳过...");
//                    continue;
//                }
//                int commit = currencyBlock - transaction.getBlockNumber().intValue() + 1;
//                if (commit <= 5) {
//                    log.info("发现确认数小于5的数据，停止扫块");
//                    flag = false;
//                    break;
//                }
//                if (transaction.getTo().trim().equals(address)) {
//                    log.info("发现一笔充值........");
//                    log.info("金额{}", toPrice(transaction.getValue()));
//                    log.info("from{}", transaction.getFrom());
//                    BigInteger gasPrice = transaction.getGasPrice().divide(new BigInteger("1000000000"));
//                    BigInteger fee = gasPrice.multiply(transaction.getGas());
//                    log.info("fee{}", df.format(fee.doubleValue() / 1000000000).toString());
//                    String txid = transaction.getHash().trim();
//                    log.info("txid：{}", txid);
//                    toMain(address, toPrice(transaction.getValue()));
//                }
//                //TO和我们的地址做比较
//                //如果有就继续判断hash有没有，没有就开始进行业务
//            }
//        }
    }

    public BigDecimal toPrice(BigInteger price){
        //除18位小数
        return new BigDecimal(price).divide(new BigDecimal(Math.pow(10,18))).setScale(6, RoundingMode.HALF_UP);
    }


    public String send(String method, String params)
            throws Exception {
        String tonce = "" + System.currentTimeMillis() * 1000L;
        String url = "https://mainnet.infura.io/v3/cee41b881e9b4a369cb3df8efe61fa35";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Json-Rpc-Tonce", tonce.toString());
        con.setRequestProperty("Content-Type", " application/json");

        String postdata = "{\"jsonrpc\":\"2.0\",\"method\":\"" + method + "\", \"params\":" + params + ", \"id\": 1}";
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postdata);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode != 200) {
            return "{\"result\":null,\"error\":" + responseCode + ",\"id\":1}";
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String result = in.readLine();
        in.close();
        return result;
    }

}
